import Vue.bgui as bgui
import bge
import sys
import GLOB
import socket
from threading import *
import time
import Client
import os
import inspect
import subprocess as subprocess


#source de la doc: https://code.google.com/p/bgui/wiki/GettingStarted
defaultFontSize = 30
nbrJoueurAllouer = 4
myIptab = ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])[0]
chat = [] 
index = 0

conteurDebut = 5


def closeDialog(dialog):
	dialog.visible = False
class BlenderUISystem(bgui.System):
	def __init__(self):      
			objects = bge.logic.getCurrentScene().objects        
			bgui.System.__init__(self, sys.path[0] + "/theme") #ugly hack because of path issues ;X
			#### CONNECT DIALOG ####
			self.connect = bgui.Frame(self, 'connect', size=[1, 1], border=2, options=bgui.BGUI_DEFAULT | bgui.BGUI_CENTERX | bgui.BGUI_CENTERY)
			size = int(self.connect.size[0] * 5)

			#--------------------------------------------------------------------------------------------------------------------------------------------------------------#

			#Fond d'écran
			self.imageBg  = bgui.Image(self.connect, 'Background','./Vue/images/bg.jpg',size=[1,1],pos=[0,0], options = bgui.BGUI_DEFAULT|bgui.BGUI_CENTERX|bgui.BGUI_CACHE) 

			#--------------------------------------------------------------------------------------------------------------------------------------------------------------#

			#Boutton pour joindre la partie
			self.buttonJoindre = bgui.ImageButton(self.connect, 'buttonJoindre', 
								default_image=("./Vue/images/Joindre.png",0,0,1,1), default2_image=("./Vue/images/Joindre.png",0,0,1,1),hover_image=("./Vue/images/Joindre3.png",0,0,1,1), 
								size=[0.4,0.10], pos=[0.005, 0.6],	options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)

			#Bouton pour creer la partie
			self.buttonCreer = bgui.ImageButton(self.connect, 'buttonCreer', 
								default_image=("./Vue/images/Creer.png",0,0,1,1), default2_image=("./Vue/images/Creer.png",0,0,1,1), hover_image=("./Vue/images/Creer2.png",0,0,1,1), 
								size=[0.4,0.10], pos=[0.005, 0.8],	options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)

			#--------------------------------------------------------------------------------------------------------------------------------------------------------------#

			#Carré gris+ chose a l'intérieur Joindre
			self.popUpImage = bgui.Image(self.connect, 'PopUp','./Vue/images/test.png',None,size=[0.40,0.95],pos=[1.25,0.025], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)

			self.flowNom = bgui.Image(self.popUpImage, 'FlowNom','./Vue/images/test.png',None,size=[0.86,0.08],pos=[0.08,0.7], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			self.labelNom = bgui.Label(self.popUpImage, 'labelNom', text="Entrez votre nom: ", pt_size = defaultFontSize, pos=[0.08, 0.8])          
			self.inputNom = bgui.TextInput(self.popUpImage, 'inputNom', "", pt_size = defaultFontSize, size=[0.85, 0.08], pos=[0.08, 0.7],
							input_options = bgui.BGUI_INPUT_NONE, options = bgui.BGUI_DEFAULT)
			
			self.flowIp = bgui.Image(self.popUpImage, 'FlowIP','./Vue/images/test.png',None,size=[0.86,0.08],pos=[0.08, 0.5], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			self.labelIP = bgui.Label(self.popUpImage, 'labelIP', text="Entrez l'adresse IP: ", pt_size = defaultFontSize, pos=[0.08, 0.6])          
			self.inputIP = bgui.TextInput(self.popUpImage, 'inputIP', "localhost", pt_size = defaultFontSize, size=[0.85, 0.08], pos=[0.08, 0.5],
							input_options = bgui.BGUI_INPUT_NONE, options = bgui.BGUI_DEFAULT)
			
			self.flowPort = bgui.Image(self.popUpImage, 'FlowPort','./Vue/images/test.png',None,size=[0.86,0.08],pos=[0.08, 0.3], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			self.labelPort = bgui.Label(self.popUpImage, 'labelPort', text="Entrez le port au besoin: ", pt_size = defaultFontSize, pos=[0.08, 0.4])                                
			self.inputPort = bgui.TextInput(self.popUpImage, 'inputPort', "41223", pt_size = defaultFontSize, size=[0.85, 0.08], pos=[0.08, 0.3],
							input_options = bgui.BGUI_INPUT_NONE, options = bgui.BGUI_DEFAULT)

			self.buttonOk = bgui.ImageButton(self.popUpImage, 'buttonConnect', 
								default_image=("./Vue/images/Connection.png",0,0,1,1),hover_image=("./Vue/images/Connection2.png",0,0,1,1), 
								size=[0.6,0.10], pos=[0.2, 0.1],	options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)

			#--------------------------------------------------------------------------------------------------------------------------------------------------------------#


			#Carré Gris bas + chose a l'intérieur Creation
			self.popUpImageCreation = bgui.Image(self.connect, 'popUpCreation','./Vue/images/test.png',None,size=[0.37,0.27],pos=[-0.62, 0.46], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)

			self.flowNomCreation = bgui.Image(self.popUpImageCreation, 'FlowNomCreation','./Vue/images/test.png',None,size=[0.86,0.24],pos=[0.08,0.54], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			self.labelNomCreation = bgui.Label(self.popUpImageCreation, 'labelNomCreation', text="Entrez votre nom: ", pt_size = defaultFontSize, pos=[0.08, 0.8])          
			self.inputNomCreation= bgui.TextInput(self.popUpImageCreation, 'inputNomCreation', "", pt_size = defaultFontSize, size=[0.85, 0.24], pos=[0.08, 0.54],
							input_options = bgui.BGUI_INPUT_NONE, options = bgui.BGUI_DEFAULT) 

			self.buttonOkCreation = bgui.ImageButton(self.popUpImageCreation, 'buttonOkCreation', 
								default_image=("./Vue/images/Connection.png",0,0,1,1),hover_image=("./Vue/images/Connection2.png",0,0,1,1), 
								size=[0.6,0.40], pos=[0.2, 0.1],	options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)



			#Affichage du lobby
			self.total = bgui.Image(self.connect, 'CarreT','./Vue/images/FrameLobbybg.png',None,size=[0.98,0.98],pos=[0.01,0.01], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			self.Droit = bgui.Image(self.total, 'CarreD','./Vue/images/FrameLobby.png',None,size=[0.471,0.83],pos=[0.50,0.14], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			self.basGauche = bgui.Image(self.total, 'CarreBG','./Vue/images/FrameLobbyJoueur.png',None,size=[0.45,0.24],pos=[0.03,0.03], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)


			#Affichage Joueur Dans le lobby
			self.joueur1 = bgui.Image(self.basGauche, 'Joueur1','./Vue/images/joueur/Joueur1.png',None,size=[0.235,0.90],pos=[0.0124,0.05], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			self.joueur2 = bgui.Image(self.basGauche, 'Joueur2','./Vue/images/joueur/Joueur2.png',None,size=[0.235,0.90],pos=[0.0124+0.2455,0.05], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			self.joueur3 = bgui.Image(self.basGauche, 'Joueur3','./Vue/images/joueur/Joueur3.png',None,size=[0.235,0.90],pos=[0.0124+0.494,0.05], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			self.joueur4 = bgui.Image(self.basGauche, 'Joueur4','./Vue/images/joueur/Joueur4.png',None,size=[0.235,0.90],pos=[0.0124+0.74,0.05], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			

			# ------ Commencer partie ------ #
			self.Demmarer = bgui.ImageButton(self.total, 'buttonDemmarer', 
								default_image=("./Vue/images/start.png",0,0,1,1),hover_image=("./Vue/images/start2.png",0,0,1,1), 
								size=[0.4,0.1], pos=[0.05, 0.39],	options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)


			# ------ Partie Chat ------ #
			self.buttonEnterJoueur = bgui.ImageButton(self.total, 'buttonEnterJoueur', 
								default_image=("./Vue/images/button/boutonenter.png",0,0,1,1),default2_image=("./Vue/images/button/boutonenter.png",0,0,1,1), click_image=("./Vue/images/button/boutonenter2.png",0,0,1,1), 
								size=[0.1,0.06], pos=[0.87,0.05],	options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)

			self.buttonEnterJoueurCreation = bgui.ImageButton(self.total, 'buttonEnterJoueurCreation', 
								default_image=("./Vue/images/button/boutonenter.png",0,0,1,1),default2_image=("./Vue/images/button/boutonenter.png",0,0,1,1), click_image=("./Vue/images/button/boutonenter2.png",0,0,1,1), 
								size=[0.1,0.06], pos=[0.87,0.05],	options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)

			self.flowMessage = bgui.Image(self.total, 'flowMessage','./Vue/images/test.png',None,size=[0.365,0.08],pos=[0.5,0.040], options = bgui.BGUI_DEFAULT|bgui.BGUI_CACHE)
			self.inputMessage = bgui.TextInput(self.total, 'inputMessage', "", pt_size = defaultFontSize, size=[0.355,0.08], pos=[0.5,0.040])
			self.messageLabel0 = bgui.Label(self.Droit, "0", "", pt_size = defaultFontSize, pos=[0.03,0.05+(0*0.09)])
			self.messageLabel1 = bgui.Label(self.Droit, "1", "", pt_size = defaultFontSize, pos=[0.03,0.05+(1*0.09)])
			self.messageLabel2 = bgui.Label(self.Droit, "2", "", pt_size = defaultFontSize, pos=[0.03,0.05+(2*0.09)])
			self.messageLabel3 = bgui.Label(self.Droit, "3", "", pt_size = defaultFontSize, pos=[0.03,0.05+(3*0.09)])
			self.messageLabel4 = bgui.Label(self.Droit, "4", "", pt_size = defaultFontSize, pos=[0.03,0.05+(4*0.09)])
			self.messageLabel5 = bgui.Label(self.Droit, "5", "", pt_size = defaultFontSize, pos=[0.03,0.05+(5*0.09)])
			self.messageLabel6 = bgui.Label(self.Droit, "6", "", pt_size = defaultFontSize, pos=[0.03,0.05+(6*0.09)])
			self.messageLabel7 = bgui.Label(self.Droit, "7", "", pt_size = defaultFontSize, pos=[0.03,0.05+(7*0.09)])
			self.messageLabel8 = bgui.Label(self.Droit, "8", "", pt_size = defaultFontSize, pos=[0.03,0.05+(8*0.09)])
			self.messageLabel9 = bgui.Label(self.Droit, "9", "", pt_size = defaultFontSize, pos=[0.03,0.05+(9*0.09)])


			# ------ Début de partie ------ #
			self.debutLabel = bgui.TextInput(self.total, "debutPartie", str(conteurDebut), pt_size = 60, size=[0.25,0.25],pos=[0.2,0.5],
																input_options = bgui.BGUI_INPUT_NONE, options = bgui.BGUI_DEFAULT)


			#--------------------------------------------------------------------------------------------------------------------------------------------------------------#

			##### BUTTON ACTIONS #####
			self.buttonOk.on_click = lambda nul: affichageLobby()
			self.buttonJoindre.on_click = lambda nul: menuConnectionPartie()
			self.buttonEnterJoueur.on_click = lambda nul: ecrireMessage(self.inputNom.text)
			self.buttonEnterJoueurCreation.on_click = lambda nul: ecrireMessage(self.inputNomCreation.text)
			self.Demmarer.on_click = lambda nul: Client.demmarerPartie()
			self.buttonCreer.on_click = lambda nul : menuCreationPartie()
			self.buttonOkCreation.on_click = lambda	nul : creationPartie()

			#--------------------------------------------------------------------------------------------------------------------------------------------------------------#

			#---- Fonctions ----#

			def menuPrincipale():
				self.popUpImageCreation.visible = False
				self.Demmarer.visible = False
				self.debutLabel.visible = False

				self.joueur1.visible = False
				self.joueur2.visible = False
				self.joueur3.visible = False
				self.joueur4.visible = False

				self.popUpImage.visible = False
				self.buttonJoindre.visible = True
				self.connect.visible = True
				self.buttonCreer.visible = True
				self.total.visible = False
	   

			def menuCreationPartie():
				self.buttonJoindre.move([0.005, 0.25], 300)
				self.popUpImage.move([1.25,0.025], 1000)
				self.popUpImageCreation.move([0.029, 0.46],800)
				self.popUpImageCreation.visible = True

			def menuConnectionPartie():
				self.popUpImageCreation.move([-0.62, 0.46],600)
				self.buttonJoindre.move([0.005, 0.6], 1000)
				self.popUpImage.move([0.55,0.025], 800)
				self.popUpImage.visible = True
				self.buttonJoindre.visible = True
				self.connect.visible = True
				self.total.visible = False

			def ecrireMessage(nom):
				text = nom + ": " + self.inputMessage.text
				Client.ecrireMessage(text)
				self.inputMessage.text = ""

			def affichageLobby():
				#self.Demmarer.visible = True
				self.buttonCreer.visible = False
				Client.initClient(self.inputNom.text, self.inputIP.text, self.inputPort.text)
				self.popUpImage.visible = False
				self.buttonJoindre.visible = False
				self.connect.visible = True
				self.total.visible = True
				self.buttonEnterJoueurCreation.visible = False
				GLOB.lobbyBool = True

			def creationPartie():
				folder = os.getcwd()
				os.chdir(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))
				os.chdir(os.pardir)
				os.chdir(os.getcwd()+ '\Serveur')
				subprocess.Popen(["c:\Python32\Python.exe", 'Server.py']).pid # ouverture du serveur
				os.chdir(folder)											  # remettre le dossier au client sinon vue plante...
				time.sleep(0.7)
				Client.initClient(self.inputNomCreation.text, "Localhost", "41223")
				self.buttonCreer.visible = False
				self.popUpImageCreation.visible = False
				self.buttonJoindre.visible = False
				self.connect.visible = True
				self.total.visible = True
				self.buttonEnterJoueur.visible = False
				self.Demmarer.visible = True
				GLOB.lobbyBool = True

			menuPrincipale()

			# Create a keymap for keyboard input
			self.keymap = {getattr(bge.events, val): getattr(bgui, val) for val in dir(bge.events) if val.endswith('KEY') or val.startswith('PAD')} 

	def affichageJoueurs(self, nbrJoueur):
		if GLOB.nombreJoueurs == 1:
			self.joueur1.visible = True
		elif GLOB.nombreJoueurs == 2:
			self.joueur1.visible = True
			self.joueur2.visible = True
		elif GLOB.nombreJoueurs == 3:
			self.joueur1.visible = True
			self.joueur2.visible = True
			self.joueur3.visible = True
		elif GLOB.nombreJoueurs == 4:
			self.joueur1.visible = True
			self.joueur2.visible = True
			self.joueur3.visible = True
			self.joueur4.visible = True


	def main(self):
			"""A high-level method to be run every frame.
					This handles things like sending mouse and keyboard events to BGUI."""
			
			# Handle the mouse
			mouse = bge.logic.mouse
			mouse_events = mouse.events
			
			# Get the position
			pos = list(mouse.position)
			pos[0] *= bge.render.getWindowWidth()
			pos[1] = bge.render.getWindowHeight() - (bge.render.getWindowHeight() * pos[1])
							
			# Get the mouse state
			if mouse_events[bge.events.LEFTMOUSE] == bge.logic.KX_INPUT_JUST_ACTIVATED:
					mouse_state = bgui.BGUI_MOUSE_CLICK
			elif mouse_events[bge.events.LEFTMOUSE] == bge.logic.KX_INPUT_JUST_RELEASED:
					mouse_state = bgui.BGUI_MOUSE_RELEASE
			elif mouse_events[bge.events.LEFTMOUSE] == bge.logic.KX_INPUT_ACTIVE:
					mouse_state = bgui.BGUI_MOUSE_ACTIVE
			else:
					mouse_state = bgui.BGUI_MOUSE_NONE
			
			# Send the position and state to BGUI
			self.update_mouse(pos, mouse_state)
			
			# Handle the keyboard
			keyboard = bge.logic.keyboard
			
			# Get the keys
			key_events = keyboard.events
			is_shifted = key_events[bge.events.LEFTSHIFTKEY] == bge.logic.KX_INPUT_ACTIVE or \
									key_events[bge.events.RIGHTSHIFTKEY] == bge.logic.KX_INPUT_ACTIVE
									
			# Update keys for BGUI
			for key, state in keyboard.events.items():
					if state == bge.logic.KX_INPUT_JUST_ACTIVATED:
							self.update_keyboard(self.keymap[key], is_shifted)
			
			# Now setup the scene callback so we can draw
			bge.logic.getCurrentScene().post_draw = [self.render]
			

blenderUI = BlenderUISystem()

def refreshMessage(text):
		print(text)
		if len(chat) == 10:
			chat.pop()

		chat.insert(0, text)


def main(cont):
	"""main() method to attach to a module controller in the BGE"""
	
	own = cont.owner
	mouse = bge.logic.mouse

	if 'sys' not in own:
			# Create our system and show the mouse
			own['sys'] = BlenderUISystem()
			mouse.visible = True
	else:
			# The system's been created, so just run it
			own['sys'].main()
			if GLOB.lobbyBool and not GLOB.partieEnCours:
				own['sys'].affichageJoueurs(GLOB.nombreJoueurs)
			if GLOB.partieEnCours:
				own['sys'].connect.visible = False
			if chat != None and not GLOB.partieEnCours:
				for i in range(len(chat)):
					if i== 0:
						own['sys'].messageLabel0.text = chat[i]
						own['sys'].messageLabel0.visible = True
					elif i== 1:
						own['sys'].messageLabel1.text = chat[i]
						own['sys'].messageLabel1.visible = True
					elif i== 2:
						own['sys'].messageLabel2.text = chat[i]
						own['sys'].messageLabel2.visible = True
					elif i== 3:
						own['sys'].messageLabel3.text = chat[i]
						own['sys'].messageLabel3.visible = True
					elif i== 4:
						own['sys'].messageLabel4.text = chat[i]
						own['sys'].messageLabel4.visible = True
					elif i==5:
						own['sys'].messageLabel5.text = chat[i]
						own['sys'].messageLabel5.visible = True
					elif i== 6:
						own['sys'].messageLabel6.text = chat[i]
						own['sys'].messageLabel6.visible = True
					elif i== 7:
						own['sys'].messageLabel7.text = chat[i]
						own['sys'].messageLabel7.visible = True
					elif i== 8:
						own['sys'].messageLabel8.text = chat[i]
						own['sys'].messageLabel8.visible = True
					elif i== 9:
						own['sys'].messageLabel9.text = chat[i]
						own['sys'].messageLabel9.visible = True
